package per.mnxc.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import per.mnxc.exception.CustomException;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @BelongsProject: spring_stu
 * @BelongsPackage: per.mnxc.common
 * @Author: mnxc
 * @CreateTime: 2022-11-03  15:42
 * @Description: 全局异常处理
 * @Version: 1.0
 */
@RestControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> sqlExceptionHandler(SQLIntegrityConstraintViolationException ex){
        // log.error(ex.getMessage());
        if(ex.getMessage().contains("Duplicate entry")){
            String[] s = ex.getMessage().split(" ");
            return R.error(s[2]+"已存在！");
        }

        return R.error("SqlError");
    }
    @ExceptionHandler(CustomException.class)
    public R<String> customExceptionHandler(CustomException ex){
        return R.error(ex.getMessage());
    }
    // @ExceptionHandler(Exception.class)
    public R<String> exceptionHandler(Exception ex){
        log.error(ex.getMessage());
        return R.error("未知错误");
    }
}
